import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:wms/utils/utils.dart';
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart'; 
import 'package:flutter/services.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';

class ReceivingScreen extends StatefulWidget {
  const ReceivingScreen({super.key});

  @override
  _ReceivingScreenState createState() => _ReceivingScreenState();
}

class _ReceivingScreenState extends State<ReceivingScreen> with WidgetsBindingObserver {
  final _barcodeController = TextEditingController();
  bool _isButtonEnabled = false;
  bool _isLoading = false;
  bool _isReadOnly = false;
  final FocusNode _barcodeFocusNode = FocusNode();
  List<Map<String, dynamic>> availableShipmentLines = [];
  Map<String, dynamic>? _selectedShipmentLine; // 选中的条目
  bool _showSelectionList = false;
  String? itemNumber;
  String? productCode;
  String? lpnNumber;
  bool _isKeyboardVisible = false;
  int? warehouseId;
  late double _fontScale;
  
  // 定义文本样式常量
  static const double _baseFontSize = 13.0;
  static const double _smallFontSize = 12.0;
  
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _barcodeController.addListener(_updateButtonState);
    _barcodeFocusNode.addListener(_handleFocusChange);
    
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _resetKeyboardState();
      }
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _barcodeController.removeListener(_updateButtonState);
    _barcodeController.dispose();
    _barcodeFocusNode.removeListener(_handleFocusChange);
    _barcodeFocusNode.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetKeyboardState();
    }
  }

  void _resetKeyboardState() {
    setState(() {
      _isKeyboardVisible = false;
    });
    _barcodeFocusNode.unfocus();
    Future.delayed(const Duration(milliseconds: 50), () {
      if (mounted) {
        _barcodeFocusNode.requestFocus();
        _hideKeyboard();
        Future.delayed(const Duration(milliseconds: 100), () {
          if (mounted) _hideKeyboard();
        });
      }
    });
  }

  void _showKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    } catch (e) {
      print('显示键盘失败: $e');
    }
  }

  void _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
    }
  }

  void _handleFocusChange() {
    if (_barcodeFocusNode.hasFocus && !_isKeyboardVisible) {
      _hideKeyboard();
    }
  }

  // 恢复toggleKeyboardVisibility方法
  void _toggleKeyboardVisibility() {
    setState(() {
      _isKeyboardVisible = !_isKeyboardVisible;
    });

    FocusScope.of(context).requestFocus(_barcodeFocusNode);
    
    Future.delayed(const Duration(milliseconds: 150), () {
      if (_isKeyboardVisible) {
        _showKeyboard();
      } else {
        _hideKeyboard();
      }
    });
  }

  void _updateButtonState() {
    final hasText = _barcodeController.text.trim().isNotEmpty;
    if (_isButtonEnabled != hasText) {
      setState(() {
        _isButtonEnabled = hasText;
      });
    }
  }

  void _parseBarcode(String value) {
    try {
      itemNumber =  Utils.parseQRCode(value, 'order number');
      productCode =  Utils.parseQRCode(value, 'product code');
      setState(() {
        if (itemNumber != null) {
          _barcodeController.text = itemNumber.toString();
        }
        _barcodeController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: _barcodeController.text.length,
        );
      });
    } catch (e) {
      throw Exception('$e');
    }
  }

  Future<Map<String, dynamic>> _fetchCheckinDetails(String barcode) async {
    String? apiParam;
    if(lpnNumber != null){
      apiParam = lpnNumber;
    }
    else if(itemNumber != null){
       apiParam = itemNumber;
    }
    else{
      apiParam = barcode;
    }
    const apiUrl = ApiService.baseURL + ApiService.fetchReceiving;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }
    
    try {
      final response = await http.get(
        Uri.parse('$apiUrl$apiParam'),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'X-Client-Type':'app'
        },
      );
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        final jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if (jsonData['code'] == 401) {
          AuthService().logout(context);
          throw Exception('The session has expired, Please log in again.');
        } else {
          throw Exception('${jsonData['msg']}');
        }
      } else {
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  void _navigateToNextScreen(Map<String, dynamic> shipmentLine) {
    print('shipmentLine--$shipmentLine');
    Navigator.pushReplacementNamed(
      context,
      '/inbound/receiving-detail-item',
      arguments: shipmentLine,
    );
  }

  void _handleSubmitted(String value) async {
    if (!_isButtonEnabled || _isLoading) return;
    if(value.contains(':')){
      _parseBarcode(value);
    }
    setState(() {
      _isLoading = true;
      _isReadOnly = true;
      _showSelectionList = false;
      _isKeyboardVisible = false;
      _hideKeyboard();
    });
    
    try {
      final responseData = await _fetchCheckinDetails(value.trim());
      if (!mounted) return;
      
      final List<dynamic> dataList = responseData['data'];

      // List<Map<String, dynamic>> allList = List<Map<String, dynamic>>.from(dataList);
      // String status = dataList[0]['status'].toString().toLowerCase();
      // for (var receiving in allList) {
      //   if(status == 'received' || status == 'shipped' || status == 'delivered'){
      //     allList.remove(receiving);
      //   }
      // }
      if (dataList.isEmpty) {
        throw Exception(responseData['msg']);
      }
      else if (dataList.length == 1) {
        String status = dataList[0]['status'].toString().toLowerCase();
        if(status == 'received'){
          throw Exception('Item already received, please change another QR code.'); 
        }
        else if(status != 'receiving' && status != 'progressing'){
          throw Exception('Please checkin item first.'); 
        }
        else{
          _navigateToNextScreen(dataList[0]);
        }
      }
      else {
        List<Map<String, dynamic>> allList = List<Map<String, dynamic>>.from(dataList);
        String status = dataList[0]['status'].toString().toLowerCase();
        for (var receiving in allList) {
          if(status == 'received' || status == 'shipped' || status == 'delivered'){
            allList.remove(receiving);
          }
        }
        setState(() {
          availableShipmentLines = allList;
          _selectedShipmentLine = null; // 初始不选中任何数据
          _showSelectionList = true;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (!mounted) return;
      MessageBox.showMessageBox(context,e,isError:true);
      setState(() {
        _isLoading = false;
        _isReadOnly = false;
      });
    }
    finally{
      if(mounted){
        setState(() {
          _isLoading = false;
          _isReadOnly = false;
        });
        _resetKeyboardState();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    
    // 获取屏幕尺寸信息
    final screenSize = MediaQuery.of(context).size;
    
    // 计算字体缩放比例 (基于屏幕宽度)
    final double scaleFactor = screenSize.width < 600 
        ? (screenSize.width / 600).clamp(0.85, 1.0) 
        : 1.0;

    return Scaffold(
      appBar: AppBar(
        title: Text('Receiving',style: TextStyle(fontSize: 18 * _fontScale),),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pushNamed(context, '/inbound'),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      body: GestureDetector(
        // 点击空白区域时取消所有输入框焦点
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        // 确保空白区域也能响应点击事件
        behavior: HitTestBehavior.opaque,
        child:Padding(
          padding: EdgeInsets.all(32 * scaleFactor),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child:Container(
                      height: 48 * scaleFactor,
                      child: TextField(
                        readOnly: _isReadOnly,
                        keyboardType: TextInputType.text,
                        controller: _barcodeController,
                        focusNode: _barcodeFocusNode,
                        autofocus: false,
                        decoration: InputDecoration(
                          labelText: 'Or Enter Barcode Manually',
                          border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
                          contentPadding: EdgeInsets.symmetric(vertical: 14 * scaleFactor, horizontal: 12 * scaleFactor),
                          prefixIcon: const Icon(Icons.qr_code),
                          suffixIcon: IconButton(
                            icon: Icon(
                              _isKeyboardVisible ? Icons.keyboard_hide : Icons.keyboard,
                              color: const Color(0xFF008363),
                            ),
                            onPressed: _toggleKeyboardVisibility,
                            splashRadius: 24,
                            padding: EdgeInsets.all(8 * scaleFactor),
                            constraints: BoxConstraints.tightFor(width: 48 * scaleFactor, height: 48 * scaleFactor),
                          ),
                          hintText: _isKeyboardVisible 
                              ? 'Type barcode here...' 
                              : 'Ready to scan (tap keyboard icon to type)',
                        ),
                        onChanged: (value) => _updateButtonState(),
                        onSubmitted: _handleSubmitted,
                        onTap: () {
                          if (_barcodeController.text.isNotEmpty) {
                            _barcodeController.selection = TextSelection(
                              baseOffset: 0,
                              extentOffset: _barcodeController.text.length,
                            );
                          }
                        },
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 60 * scaleFactor,
                    height: 48 * scaleFactor,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(horizontal: 10 * scaleFactor, vertical: 10 * scaleFactor),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(0),
                        ),
                        backgroundColor: _isButtonEnabled 
                            ? const Color(0xFF008363) 
                            : Colors.grey,
                      ),
                      onPressed: _isButtonEnabled && !_isLoading
                          ? () => _handleSubmitted(_barcodeController.text)
                          : null,
                      child: _isLoading 
                          ? SizedBox(
                              width: 20 * scaleFactor,
                              height: 20 * scaleFactor,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                color: Colors.white,
                              ),
                            )
                          : Text(
                              'GO', 
                              style: TextStyle(fontSize: 15 * scaleFactor, color: Colors.white),
                            ),
                    ),
                  ),
                ],
              ),
              
              if (_showSelectionList) ...[
                SizedBox(height: 20 * scaleFactor),
                SizedBox(height: 10 * scaleFactor),
                Expanded(
                  child: ListView.builder(
                    itemCount: availableShipmentLines.length,
                    itemBuilder: (context, index) {
                      final shipment = availableShipmentLines[index];
                      final isSelected = _selectedShipmentLine == shipment;
                      
                      return Card(
                        elevation: 2,
                        margin: EdgeInsets.symmetric(vertical: 4 * scaleFactor),
                        child: Container(
                          color: isSelected ? Colors.green[50] : null,
                          child: ListTile(
                            title: Text(
                              shipment['order_info']?['order_number'] ?? 'N/A',
                              style: TextStyle(
                                fontSize: _baseFontSize * scaleFactor,
                                color: isSelected ? Colors.green : Colors.black,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            subtitle: Text(
                              'Shipment code: ${shipment['shipment_code'] ?? 'N/A'}     Check time: ${shipment['checkin_time'] ?? 'N/A'}',
                              style: TextStyle(
                                fontSize: _smallFontSize * scaleFactor,
                                color: isSelected ? Colors.green : Colors.black,
                              ),
                            ),
                            onTap: () {
                              setState(() {
                                // 点击已选中项则取消选中，否则选中当前项
                                _selectedShipmentLine = isSelected ? null : shipment;
                              });
                            },
                          ),
                        ),
                      );
                    },
                  ),
                ),
                SizedBox(height: 10 * scaleFactor),
                SizedBox(
                  width: double.infinity,
                  height: 50 * scaleFactor,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF008363),
                      disabledBackgroundColor: Colors.grey,
                      padding: EdgeInsets.symmetric(vertical: 15 * scaleFactor),
                    ),
                    // 只有选中数据时按钮才可用
                    onPressed: _selectedShipmentLine != null 
                        ? _handleSelectionConfirmed 
                        : null,
                    child: Text(
                      'Confirmed',
                      style: TextStyle(fontSize: 16 * scaleFactor, color: Colors.white),
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      )
    );
  }

  void _handleSelectionConfirmed() {
    if (_selectedShipmentLine != null) {
      _navigateToNextScreen(_selectedShipmentLine!);
    }
  }
}
